package com.atguigu.day03;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

//100个线程，每个线程加100次，求最后的number值
public class CASDemo {
        private int num;
        //对num进行操作的时候要加锁
    //不使用原子类AtomicInteger
        public synchronized  void setNum(){
           num++;
        }
        public Integer getNum(){
            return num;
        }

        //使用原子类AtomicInteger保证线程安全
    AtomicInteger atomicInteger = new AtomicInteger(0);

    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }

    public void setAtomicInteger() {
        atomicInteger.getAndIncrement();
    }

    public static void main(String[] args) throws InterruptedException {
            CASDemo casDemo = new CASDemo();
            CASDemo casDemo1 = new CASDemo();
        CountDownLatch countDownLatch = new CountDownLatch(100);

        for (int i = 0; i < 100; i++) {
             new Thread(() -> {
                 for (int j = 0; j < 100; j++) {
                     casDemo.setNum();
                     casDemo1.setAtomicInteger();

                 }
                 //每一个线程执行后countDownLatch都要减少一
                 countDownLatch.countDown();
                     }, "A").start();
        }
        //线程睡眠几秒
//        try {
//            TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {throw new RuntimeException(e);}
        countDownLatch.await();
        System.out.println("num值为:"+casDemo.getNum());
        System.out.println("使用原子类后num的值为："+casDemo1.getAtomicInteger());
    }
}
